package com.book.iphone;

import com.book.book.domain.*;
import com.book.book.service.*;
import com.book.iphone.domain.QueueListItem;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sun.tools.javac.jvm.Items;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：青松
 * 日期： 2018/3/22
 *///预约图书详情
@Controller
@RequestMapping("/book")
public class BookAppointmentController {
    @Autowired
    QueueService queueService;
    @Autowired
    BooksService booksService;
    @Autowired
    ApplyService applyService;
    @Autowired
    UsersService usersService;
    @Autowired
    AppointmentService appointmentService;
    @Autowired
    BooklogService booklogService;

    @RequestMapping("/appointment/{userId}/{bookName}")
    String appointmentInfo(@PathVariable("userId") String userId
            , @PathVariable("bookName") String bookName, Model model) {
        Map<String, Object> map = new HashMap<>();
        map.put("bookName", bookName);
        List<BooksDO> booksDOList = booksService.list(map);
        BooksDO booksDO = booksDOList.get(0);
        model.addAttribute("books", booksDO);
        List<QueueDO> queueDOList = queueService.getQueueItem(userId, bookName);//list.size只为 1
        QueueListItem before = new QueueListItem();//上一个用户
        QueueListItem next = new QueueListItem();//下一个用户
        Gson gson = new Gson();
        int index = 0;
        int count = 0;//计数器
        int usering = 0;//图书状态判断 0； 1 接收图书； 2；漂流图书
        if (queueDOList.size() != 0) {
            for (int i = 0; i < queueDOList.size(); i++) {
                String json = queueDOList.get(i).getQueue();
                List<QueueListItem> items = gson.fromJson(json, new TypeToken<List<QueueListItem>>() {
                }.getType());
                for (int j = 0; j < items.size(); j++) {
                    if (items.get(j).getUserId().equals(userId)) {
                        index = j;//保存用户在队列中的位置索引
                        break;
                    }
                    count++;
                }
                if (index == 0) {//位于队首
                    model.addAttribute("before", items.get(index));
                    if (items.size() > 1) {//不能使用三目表达式（没有成功）
                        model.addAttribute("next", items.get(index + 1));
                    } else {
                        model.addAttribute("next", items.get(index));
                    }
                } else if (index == items.size() - 1) {//位于对尾
                    model.addAttribute("next", items.get(index));
                    if (items.size() > 1) {//不能使用三目表达式（没有成功）
                        model.addAttribute("before", items.get(index - 1));
                    } else {
                        model.addAttribute("before", items.get(index));
                    }
                } else {
                    model.addAttribute("next", items.get(index + 1));
                    model.addAttribute("before", items.get(index - 1));
                }
                if (count == 1 && queueDOList.get(0).getRedundance1().equals("2")) {
                    usering = 1;
                }
                model.addAttribute("usering", usering);//判断图书的状态
            }
        }

        model.addAttribute("count", count);
        model.addAttribute("userId", userId);
        return "book/phone/html/bookAppointment";
    }

    /**
     * 接收图书后
     * 预约表中删除用户预约信息
     * log日志表中添加部分用户信息，利用next_id查出在用户手中的书籍，漂流走的时候在完善用户信息（漂流列表中添加信息）
     * 队列表中删除用户上一站的信息，使用户置于队列的首部
     */
    @RequestMapping("/receivebook/{bookName}/{beforeUserId}")
    public String receivebook(HttpServletRequest request
            ,@PathVariable("bookName") String bookName
            ,@PathVariable("beforeUserId") String beforeUserId) {
        String userId = "";
        int applyId=0;
        UsersDO usersDO = (UsersDO) request.getSession().getAttribute("userInfo");
        if (usersDO == null) {
            return "redirect:/iphone/login";
        } else {
            userId = usersDO.getUserId();
            //获得bookID
            Map<String,Object> applyMap=new HashMap<>();
            applyMap.put("bookName",bookName);
            applyMap.put("userId",userId);
            ApplyDO applyDO=applyService.list(applyMap).get(0);
            //添加log表中用户信息
            //apply主键ID是全局的bookId
            BooklogDO booklogDO=new BooklogDO();
            booklogDO.setBookId(applyDO.getId());
            booklogDO.setHolderId(userId);
            booklogDO.setReceiveTime(new Date());
            booklogDO.setSentimentText("o11iD1NL37FWYY5IfPv85NE5YYIE");//漂流列表标识
            booklogService.save(booklogDO);//漂流日志表中添加数据
//[{"seq":1,"nickName":"青松","address":"河南省周口市周口师范学院","phone":"13033952759","userId":"o11iD1PshemlUwMJ7BuBF3kcub4E"},{"seq":2,"nickName":"长远","address":"河南省周口市周口师范图书馆","phone":"13033952733","userId":"o11iD1PshemlUwMJ7BuBF3kcub4E"}]
            Map<String,Object> appointmentMap=new HashMap<>();
            appointmentMap.put("bookName",bookName);
            appointmentMap.put("userId",userId);
            List<AppointmentDO> appointmentDOList=appointmentService.list(appointmentMap);
            applyId=appointmentDOList.get(0).getId();
            int a=appointmentService.remove(applyId);//预约表中删除用户信息
            if (a==1){
                usersDO.setBorrowNum(usersDO.getBorrowNum() + 1);
                usersService.update(usersDO); //更新数据
                request.getSession().setAttribute("userInfo", usersDO);//更新session
            }
            List<QueueDO> queueDOList=queueService.getQueueItem(userId,bookName);
            QueueDO queueDO=queueDOList.get(0);
            String json=queueDO.getQueue();
            Gson gson=new Gson();
            List<QueueListItem> items=gson.fromJson(json,new TypeToken<List<QueueListItem>>(){}
                                                        .getType());
            boolean flag=false;
            if (!beforeUserId.equals(userId)){
                for (int i=0;i<items.size();i++){
                    if (items.get(i).getUserId().equals(beforeUserId)){
                        items.remove(i);
                        flag=true;
                        break;
                    }
                }
            }
            if (flag){//更新数据
                String queuejson=gson.toJson(items);
                queueDO.setQueue(queuejson);
                queueService.update(queueDO);
            }
        }
        return "book/phone/html/drift_list";
    }
}
